from qcloudsms_py import SmsSingleSender
from qcloudsms_py.httpclient import HTTPError
from . import settings
import random
from luffyapi.utils.logger import logger


# 生成四位随机数字验证码
def get_code():
    code = ''
    for i in range(4):
        code += str(random.randint(0,9))
    return code


def send_msg(phone, code, duration):
    # 指定模板 ID 单发短信
    ssender = SmsSingleSender(settings.appid, settings.appkey)
    params = [code, duration]  # 当模板没有参数时，`params = []`
    try:
        result = ssender.send_with_param(
            86,
            phone,
            settings.template_id,
            params,
            sign=settings.sms_sign,
            extend="",
            ext=""
        )
        if result.get("result") == 0:
            return True
        else:
            print(result)
            return False

    except Exception as e:
        logger.error("手机号：%s短信发送失败，错误为：%s" % (phone, str(e)))

